const {
  userServerError,
  userAlreadyExsitd,
  userDoesNotExsit,
} = require("../constant/err.type");
const {
  createUser,
  checkWebUserDoesExsit,
  checkWebUserLogin,
  getWebUserList,
  deleteUser,
} = require("../service/webUser.service");
const { USER_SECRET } = require("../config/config.default");
const jwt = require("jsonwebtoken");
class WebUserController {
  // 用户登录控制器
  async webLogin(ctx, next) {
    const { username, pwd } = ctx.request.body;
    console.log(username, pwd);
    try {
      if (await checkWebUserDoesExsit(username)) {
        const res = await checkWebUserLogin(username, pwd);
        const token = jwt.sign(res, USER_SECRET, {
          expiresIn: "1h",
        });
        ctx.response.body = {
          code: "10000",
          message: `登录成功`,
          data: {
            token,
          },
        };
        // return
      } else {
        ctx.app.emit("error", userDoesNotExsit, ctx);
      }
    } catch (error) {
      console.log(error);
    }
  }
  // 获取管理端用户信息
  async webUserInfo(ctx, next) {
    const { username } = ctx.request.body;
    try {
      if (await checkWebUserDoesExsit(username)) {
        const res = await checkWebUserLogin(username);
        ctx.response.body = {
          code: "10000",
          message: `获取用户信息成功`,
          data: res,
        };
      } else {
        ctx.app.emit("error", userDoesNotExsit, ctx);
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 创建用户控制器
  async createUser(ctx, next) {
    const { username, password, role_type } = ctx.request.body;
    try {
      if (await checkWebUserDoesExsit(username)) {
        ctx.app.emit("error", userAlreadyExsitd, ctx);
        return;
      }
      const result = await createUser(username, password, role_type);
      console.log(result);
      // if (result.code === "10002") {
      //   ctx.response.status = 409;
      // }
      if (result) {
        ctx.response.body = result;
      }
    } catch (error) {
      console.log(error);
      ctx.app.emit("error", userServerError, ctx);
    }
  }

  // 获取用户列表控制器
  async getUserList(ctx, next) {
    const { pageNum = 1, pageSize = 10, username = "" } = ctx.query;
    const res = await getWebUserList(pageNum, pageSize, username);
    ctx.response.body = {
      code: "10010",
      message: "获取用户列表成功",
      data: res,
    };
    await next();
  }

  // 删除用户控制器
  async deleteUser(ctx, next) {
    const { id } = ctx.request.body;
    const res = await deleteUser(id);
    ctx.response.body = {
      code: "10000",
      message: "删除用户成功",
      data: res,
    };
    await next();
  }

  // 退出登陆
  async logout(ctx, next) {
    // 清除token
    ctx.response.body = {
      code: "10000",
      message: "退出登录成功",
      data: {},
    };
    await next();
  }
}

module.exports = new WebUserController();
